package com.zhmsky.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhmsky.entity.User;
import com.zhmsky.model.ResultMap;
import com.zhmsky.service.UserService;
import com.zhmsky.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @description 模拟登录请求
 * @author zhmsky
 * @date 2021/12/5 17:41
 */
@Controller
@ResponseBody
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private ResultMap resultMap;

    /**
     * @description 用户登录，用户认证成功会返回Token信息(无需任何权限)
     * @param username 账号
     * @param password 密码
     * @return
     */
    @PostMapping("/login")
    public ResultMap login(@RequestParam("username") String username, @RequestParam("password") String password) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        User user = userService.getOne(userQueryWrapper);
        if (user == null) {
            return resultMap.fail().code(401).message("用户名错误!");
        } else if (!user.getPassword().equals(password)) {
            return resultMap.fail().code(402).message("密码错误!");
        } else {
            HashMap<String, String> tokenMap = new HashMap<>();
            tokenMap.put("username", username);
            return resultMap.success().code(200).message(JwtUtils.getToken(tokenMap));
        }
    }

    /**
     * @description 统一未授权接口（所有未授权访问都会被转发到该请求）
     * @param message 这是路径变量
     * @return
     */
    @GetMapping("/unauthorized/{message}")
    public ResultMap unauthorized(@PathVariable String message){
        return resultMap.fail().code(401).message(message);
    }


}

